import { ChatModeEnums } from '../utils/enums'
import {Member} from "../lib/Member";
export default function(app) {
  const { socket, rooms } = app.locals;
  const { userId, username } = socket.handshake.query;

  // 发送给客户端的 通知消息
  socket.on('notice', function(data, cb) {

    console.log('退订', data.userId);
    if(data.userId === userId) {
      cb('ffffffffffffffff----');
    }
  });

  socket.on('onlineUsers', function(cb) {
    const { members } = app.locals;
    // 通知当前房间的其他人，但是自己并不收到消息
    // socket.broadcast.to(data.roomId).emit('onlineUsers', { members: Object.values(members) });

    // 回调
    if (cb) {
      cb({status: 'ok', members: Object.values(members).map((member) => (member as Member).json()) })
    }
  });

  // 抢麦
  socket.on('gainSpeak', function(data: any, cb) {
    const { classId } = data.room;
    const __room = rooms[classId] || {};

    if (__room.type === ChatModeEnums.INTERCOM && __room.speaker === null) {
      socket.broadcast.to(data.roomId).emit('gainSpeak', { member: { userId, username } });
      cb && cb({status: 'ok' })
    } else {
      cb && cb({status: 'fail', member: __room.speaker })
    }
  });

  // 释放麦
  socket.on('freeSpeak', function(data, cb) {
    const { classId } = data.room;
    const __room = rooms[classId] || {};

    if (__room.type === ChatModeEnums.INTERCOM && __room.speaker !== null) {
      socket.broadcast.to(data.roomId).emit('freeSpeak', { member: { userId, username } });
      cb && cb({status: 'ok' })
    } else {
      cb && cb({status: 'fail', member: __room.speaker })
    }
  });
}
